// 取消令牌管理器
// @/utils/http/CancelTokenManager.ts

import type { CancelToken } from '@/types/http'

export class CancelTokenManager {
  private tokens: Set<CancelToken> = new Set()

  // 创建取消令牌
  create(): CancelToken {
    let cancel: ((reason?: any) => void) | undefined

    const promise = new Promise((resolve) => {
      cancel = (reason?: any) => {
        token.reason = reason
        resolve(reason)
      }
    })

    const token: CancelToken = {
      promise,
      reason: undefined,
      cancel: (reason?: any) => {
        if (!token.reason) {
          cancel!(reason)
          this.tokens.delete(token)
        }
      }
    }

    this.tokens.add(token)
    return token
  }

  // 取消所有请求
  cancelAll(reason?: any): void {
    this.tokens.forEach(token => {
      if (!token.reason) {
        token.cancel(reason || '所有请求已取消')
      }
    })
    this.tokens.clear()
  }

  // 检查是否已取消
  static isCancel(value: any): boolean {
    return !!(value && value.__CANCEL__)
  }

  // 创建取消原因
  static createCancelReason(message?: string): any {
    return {
      message: message || '请求已取消',
      __CANCEL__: true
    }
  }

  // 获取活跃的令牌数量
  getActiveCount(): number {
    let count = 0
    this.tokens.forEach(token => {
      if (!token.reason) {
        count++
      }
    })
    return count
  }

  // 清理已使用的令牌
  cleanup(): void {
    const tokensToRemove: CancelToken[] = []
    
    this.tokens.forEach(token => {
      if (token.reason) {
        tokensToRemove.push(token)
      }
    })

    tokensToRemove.forEach(token => {
      this.tokens.delete(token)
    })
  }
} 